package com.cs342.g4.memaps;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.concurrent.ExecutionException;

import basicClasses.Friend;
import basicClasses.LoginObject;
import basicClasses.Place;
import basicClasses.PseudoPlace;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;
import asyncTasks.DeleteFriend;
import asyncTasks.DeletePlace;
import asyncTasks.GetFavoriteLocations;
import asyncTasks.GetFriends;

public class FavoritePlacesActivity extends Activity {
	
	private String curUser;
	private String curPass;
	SharedPreferences mPrefs;
	private ArrayList<PseudoPlace> favPlaces = new ArrayList<PseudoPlace>();
	private ArrayList<PseudoPlace> favPlacesFromDB = new ArrayList<PseudoPlace>();
	public static ListView listPlaces;
	private ArrayAdapter<String> listPlacesAdapter; 
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActionBar ab = getActionBar(); ab.setDisplayShowTitleEnabled(false); 
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		setContentView(R.layout.activity_favorite_places);
		
		Context mContext = this.getApplicationContext();
        mPrefs = mContext.getSharedPreferences("myPrefs", MODE_PRIVATE);
        
        curUser = mPrefs.getString("username", "");
        curPass = mPrefs.getString("password", "");
        LoginObject lo = new LoginObject(curUser,curPass);
        
        
        GetFavoriteLocations favPlacesTask = new GetFavoriteLocations();
		try {
			favPlacesFromDB = favPlacesTask.execute(lo).get();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			e1.printStackTrace();
		}
		
		populateFavPlaces favPsTask = new populateFavPlaces();
		favPsTask.execute(favPlacesFromDB);
		favPlaces.clear();
	}
	
	private class populateFavPlaces extends AsyncTask<ArrayList<PseudoPlace>, Void, ArrayList<PseudoPlace>> {

		@Override
		protected ArrayList<PseudoPlace> doInBackground(ArrayList<PseudoPlace>... params) {

			for(PseudoPlace place: params[0]){
				favPlaces.add(place);
			}

			return favPlaces;
		}

		@Override
		public void onPostExecute(ArrayList<PseudoPlace> places){

			ArrayList<String> placeNames = new ArrayList<String>();
			for(PseudoPlace place: places){
				placeNames.add(place.name);
			}

			listPlaces = (ListView) findViewById(R.id.favoritesList);    
			listPlacesAdapter = new ArrayAdapter<String>(FavoritePlacesActivity.this,
					android.R.layout.simple_list_item_1, placeNames);
			listPlaces.setAdapter(listPlacesAdapter);
			
			listPlaces.setLongClickable(true);
			listPlaces.setClickable(true);
			listPlaces.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO click to send to map and then show that location
					MainActivity.loc = (String) parent.getItemAtPosition(position);
					Intent backToMap = new Intent(FavoritePlacesActivity.this, MainActivity.class);
					startActivity(backToMap);
					finish();
				}
				
			});
			
			listPlaces.setOnItemLongClickListener(new OnItemLongClickListener() {

				@Override
				public boolean onItemLongClick(AdapterView<?> parent, View view,
						int position, long id) {
					//popup to delete a friend
					deletePlacePrompt(view);		
					return true;
				}
			});		
		}
	}
	
	public void deletePlacePrompt(final View v){
		LayoutInflater inflater = (LayoutInflater) FavoritePlacesActivity.this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.popup_deleteplace, null, false);
		final PopupWindow popup = new PopupWindow(view,300,130,true);
		Button yes = (Button) view.findViewById(R.id.yesDel);
		Button no = (Button) view.findViewById(R.id.noDel);
		TextView deleteMe = (TextView) view.findViewById(R.id.deleteMe);
		deleteMe.setText(((TextView)v).getText().toString());
		popup.showAtLocation(v, Gravity.CENTER, 10, 10);
		popup.setFocusable(true);
		
		
		yes.setOnClickListener(new OnClickListener() {
			
			@SuppressWarnings("unchecked")
			@Override
			public void onClick(View view) {
				popup.dismiss();
				LoginObject lo = new LoginObject(curUser,((TextView)v).getText().toString());
				DeletePlace deletePlace = new DeletePlace();
				try {
					deletePlace.execute(lo).get();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				} catch (ExecutionException e1) {
					e1.printStackTrace();
				}	
				
				LoginObject lo2 = new LoginObject(curUser,curPass);
				ArrayList<PseudoPlace> placesFromDB = new ArrayList<PseudoPlace>(); 
				GetFavoriteLocations favPlacesTask = new GetFavoriteLocations();
				try {
					placesFromDB = favPlacesTask.execute(lo2).get();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				} catch (ExecutionException e1) {
					e1.printStackTrace();
				}
				
				populateFavPlaces favPsTask = new populateFavPlaces();
				favPsTask.execute(placesFromDB);
				favPlaces.clear();
			}
		});
		
		no.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				popup.dismiss();
			}
		});
	}


	@Override	
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();	
		inflater.inflate(R.layout.menu_items, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item){
		switch (item.getItemId()){
		case R.id.menu_backToMap:
			Intent backToMap = new Intent(FavoritePlacesActivity.this, MainActivity.class);
			startActivity(backToMap);
			finish();
			return true;
		case R.id.menu_viewFriends:
			Intent vFriends = new Intent(FavoritePlacesActivity.this, ViewFriends.class);
			startActivity(vFriends);
			return true;
		case R.id.menu_logout:
			SharedPreferences.Editor edit = mPrefs.edit();
			edit.putString("username", "");
			edit.putString("password", "");
			edit.commit();
			
			Intent loginAct = new Intent(FavoritePlacesActivity.this, LoginActivity.class);
			startActivity(loginAct);
			finish();
			return true;
		}
		return false;
	}
	
	public boolean onPrepareOptionsMenu(Menu menu){
		MenuItem mapType = menu.findItem(R.id.menu_setMapType);
		MenuItem viewFavs = menu.findItem(R.id.menu_favorites);
		viewFavs.setVisible(false);
		mapType.setVisible(false);
		return true;		
	}
}
